#include "dbconfig.h"
#include "hashmap.h"
char* dbip = "192.168.3.101";
int main()
{
	hashmap *dpolicy,*oconfig;
	read_dbconfig(&dpolicy,&oconfig);
	datapolicy *demp = (datapolicy *)hashmap_get(dpolicy,"queryqq");
	printf("%s\n",demp->appname);
	hashmap_destroy(dpolicy);
	hashmap_destroy(oconfig);
}
int read_dbconfig(hashmap **dpolicy,hashmap **oconfig)
{
	char* dbip = "192.168.3.101";
	mysql_library_init(0,NULL,NULL);
	MYSQL *conn;
	MYSQL_RES *res_set;
	conn = mysql_init(NULL);
	if(conn == NULL)
	{
		fprintf(stderr,"mysql_init failed\n");
		exit(1);
	}
	mysql_options(conn,MYSQL_READ_DEFAULT_GROUP,"MysqlClient-Xddai");
	if (!mysql_real_connect(conn,dbip,"xddai","123456","ConfiguableDBOperator",0,NULL,0))
	{
	    fprintf(stderr, "Failed to connect to database: Error: %s\n",
		          mysql_error(conn));
		mysql_close(conn);
	}

	char *sql="select id,appname,ip,dbtable,username,passowrd,other from datapolicy";
	if(mysql_query(conn,sql) != 0)
		fprintf(stderr,"query failed\n");
	else
	{
		MYSQL_ROW row;
		int i=0;
		res_set = mysql_store_result(conn);
		if(res_set == NULL)
			fprintf(stderr,"no result set\n");
		else
		{
			*dpolicy = hashmap_create((int)mysql_num_rows(res_set)+1);
			while((row=mysql_fetch_row(res_set)) != NULL)
			{
				
				datapolicy *policy = (datapolicy *)malloc(sizeof(datapolicy));
				policy->id = atoi(row[0]);
				policy->appname = strdup((char *)row[1]);
				policy->ip =strdup((char *)row[2]);
				policy->dbtable = strdup((char *)row[3]);
				policy->username = strdup((char *)row[4]);
				policy->password = strdup((char *)row[5]);
				policy->other = strdup((char *)row[6]);
				hashmap_put(*dpolicy,policy->appname,policy);
			}

		}
	}
	sql="select id,appname,opname,sql,other from opconfig";
	if(mysql_query(conn,sql) != 0)
		fprintf(stderr,"query failed\n");
	else
	{
		MYSQL_ROW row;
		int i=0;
		res_set = mysql_store_result(conn);
		if(res_set == NULL)
			fprintf(stderr,"no result set\n");
		else
		{
			*oconfig= hashmap_create((int)mysql_num_rows(res_set)+1);
			while((row=mysql_fetch_row(res_set)) != NULL)
			{
				
				opconfig *config = (opconfig *)malloc(sizeof(opconfig));
				config->id = atoi(row[0]);
				config->appname = strdup((char *)row[1]);
				config->opname= strdup((char *)row[2]);
				config->sql= strdup((char *)row[3]);
				config->other =strdup((char *)row[4]);
				hashmap_put(*oconfig,config->appname,config);
			}

		}
	}
	mysql_close(conn);
	mysql_library_end();
}
//this function get ip accord dbsuffix and ippolicy
//dbsuffix like 1,ippolicy like "192.168.1.100:0-4|192.168.1.101:5-9"
char *getIp(char *dbsuffix,char *ippolicy)
{

}
